package com.cloud_notes.demo.common.advice;

import com.cloud_notes.demo.common.exception.CustomException;
import com.cloud_notes.demo.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

//统一异常处理
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public Result handler(Exception e){
        log.error("发生异常， e:{}",e.getMessage());
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(CustomException.class)//捕获自定义异常
    public Result customExceptionHandler(Exception e){
        log.error("发生错误，e:{}",e.getMessage());
        return Result.fail(e.getMessage());
    }


    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler
    public Result ExceptionHandler(NoResourceFoundException e){
        log.error("文件资源不存在，e:{}",e.getResourcePath());
        return Result.fail("文件资源不存在"+e.getResourcePath());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HandlerMethodValidationException.class, MethodArgumentNotValidException.class})
    public Result ExceptionHandler(Exception e){
        log.error("参数为空，e:{}",e.getMessage());
        return Result.fail("参数为空");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler
    public Result ExceptionHandler(MethodArgumentTypeMismatchException e){
        log.error("参数类型错误，e:{}",e.getMessage());
        return Result.fail("参数类型错误"+e.getMessage());
    }
}
